﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using My.GenCode.Entities;
using My.GenCode.Interface;

namespace My.GenCode.Templates
{
    public class GenAjaxPage : CodeTemplate
    {

        #region 覆盖父类的方法

        public GenAjaxPage(string tpl, IList<EntityInfo> infos, string desc) : base(tpl, infos, desc) { }

        protected override string ProcTemplate()
        {
            _tpl = this.LoopEntities(_tpl, "<<HandlerMethods>>", this.GenHandlerMethods);
            _tpl = _tpl.Replace("<<CallHandlerMethods>>", this.GenCallHandlerMethods());

            _tpl = _tpl.Replace("<FileName>", _nh.AjaxPageFileName);                 // 处理<FileName>标签
            _tpl = _tpl.Replace("<<NameSpace>>", _nh.NameSpace);                       // 处理<NameSpace>标签

            return _tpl;
        }

        protected override string OutputFilename()
        {
            return @"Website\_Ajax\" + _nh.AjaxPageFileName;
        }

        #endregion
        
        #region 私有方法,处理模板的循环标签

        private string GenHandlerMethods(string tpl, EntityInfo info)
        {
            NameHelper nh = new NameHelper(info.Name, info.Service, info.Company);

            tpl = tpl.Replace("<<HandlerClassName>>", nh.HandlerClassName);         // 处理<<HandlerClassName>>标签
            tpl = tpl.Replace("<<EntityClassName>>", nh.EntityClassName);

            tpl = tpl.Replace("<<CreateMethodName>>", nh.CreateMethodName);         // 处理<<CreateMethodName>>标签
            tpl = tpl.Replace("<<UpdateMethodName>>", nh.UpdateMethodName);         // 处理<<UpdateMethodName>>标签
            tpl = tpl.Replace("<<DeleteMethodName>>", nh.DeleteMethodName);         // 处理<<DeleteMethodName>>标签
            tpl = tpl.Replace("<<ReadDetailMethodName>>", nh.ReadDetailMethodName); // 处理<<ReadDetailMethodName>>标签
            tpl = tpl.Replace("<<ReadListMethodName>>", nh.ReadListMethodName);     // 处理<<ReadListMethodName>>标签

            return tpl;
        }
        
        private string GenCallHandlerMethods()
        {
            List<string> list = new List<string>();
            NameHelper nh;
            foreach (EntityInfo e in _infos)
            {
                nh = new NameHelper(e.Name, e.Service, e.Company);
                list.Add(nh.HandlerClassName+"Caller(op)");
            }
            return string.Join("\r\n              || ", list.ToArray());
        }

        #endregion

    }
}